/**
 * Title:        Utility Class Library<p>
 * Description:  Some useful utility classes.<p>
 */
package com.timber.util;

import java.util.*;
import java.text.*;

/**
 * A set of static methods to convert integer date to other data types
 */
public class IntDate
{

  public static final int BAD_DATE = 19000101;
  
/**
 * convert jave.util.Date to int
 * 
 * @param dt
 * @return int
 */
  public static int dateToIntDate( Date dt )
  {

    if( dt == null )
      return BAD_DATE;

    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTime( dt );

    return IntDate.gCalToIntDate( gcal );
  }

  /**
   * convert GregorianCalendar to int date
   * @param gcal
   * @return
   */
  public static int gCalToIntDate( GregorianCalendar gcal )
  {
    if( gcal == null )
      return BAD_DATE;

    int intDate =
      ( gcal.get( Calendar.YEAR ) * 10000 ) +
      ( ( gcal.get( Calendar.MONTH ) + 1 ) * 100 ) +
      gcal.get( Calendar.DAY_OF_MONTH );

    return intDate;
  }

  /**
   * convert int to java.util.Date
   * 
   * @param intDate
   * @return
   */
  public static Date intDateToDate( int intDate )
  {

    if( intDate == BAD_DATE || intDate==0 )
      return null;

    GregorianCalendar gcal = IntDate.intDateToGCal( intDate );

    return gcal.getTime();
  }

  /**
   * convert int date to GregorianCalendar
   * 
   * @param intDate
   * @return
   */
  public static GregorianCalendar intDateToGCal( int intDate )
  {

    if( intDate == BAD_DATE || intDate==0 )
      return null;

    GregorianCalendar gcal = new GregorianCalendar( intDate / 10000,
                                                    ( ( intDate % 10000 ) / 100 ) - 1,
                                                    intDate % 100,
                                                    0,
                                                    0,
                                                    0 );
    return gcal;
  }

  /**
   * convert int to String
   *
   * @param intDate
   * @return
   */
  public static String intDateToString( int intDate )
  {
    if( intDate == BAD_DATE || intDate==0 )
      return null;

    return Global.dateOnly( intDateToDate( intDate ) );
  }

  /**
   * convert String to int
   * 
   * @param sdate
   * @return
   */
  public static int stringToIntDate( String sdate )
  {
    try {
      if(sdate==null) return 0;
      Date dt = com.timber.util.Global.shortDateFormatter().parse(sdate);

      if( dt == null )
        return 0;
      else
        return dateToIntDate( dt );

    } catch( ParseException ex ) {
      return 0;
    }
  }
}
